package com.xingkong.app;

import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class WordCount {
	public static Logger logger = Logger.getLogger(WordCount.class);

	public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {

		private final static IntWritable one = new IntWritable(1);
		private Text word = new Text();

		public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
			StringTokenizer itr = new StringTokenizer(value.toString());
			while (itr.hasMoreTokens()) {
				word.set(itr.nextToken());
				context.write(word, one);
			}
		}
	}

	public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
		private IntWritable result = new IntWritable();

		public void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();
			}
			result.set(sum);
			context.write(key, result);
		}
	}

	public static void main(String[] args) throws Exception {
		/**
		 * 
		 * 环境变量配置
		 * 
		 */
		// 当以local模式运行时（不设置Configuration属性），由于运行在一个JVM中，可以不用打包成jar包，即File
		// jarFile = EJob.createTempJar("bin");可以不执行
		// 当以集群方式运行时，必须执行下面的这行语句，因为集群只能执行jar包
		File jarFile = EJob.createTempJar("bin");

		ClassLoader classLoader = EJob.getClassLoader();

		Thread.currentThread().setContextClassLoader(classLoader);

		logger = Logger.getLogger(WordCount.class);
		logger.info("开始执行！");
		System.setProperty("HADOOP_USER_NAME", "linux1");
		Configuration conf = new Configuration();
		/* 不设置下列属性，那么任务将会以local模式运行 */
		// conf.set("fs.default.name", "hdfs://192.168.99.101:8020");
		// conf.set("hadoop.job.user", "hadoop");
		// conf.set("mapreduce.framework.name", "yarn");
		// conf.set("mapreduce.jobtracker.address", "192.168.99.101:9001");
		// conf.set("yarn.resourcemanager.hostname", "192.168.99.101");
		// conf.set("yarn.resourcemanager.admin.address",
		// "192.168.99.101:8033");
		// conf.set("yarn.resourcemanager.address", "192.168.99.101:8032");
		// conf.set("yarn.resourcemanager.resource-tracker.address",
		// "192.168.99.101:8031");
		// conf.set("yarn.resourcemanager.scheduler.address",
		// "192.168.99.101:8030");
		// conf.set("mapreduce.jobhistory.address", "192.168.99.101:10020");
		// conf.set("mapreduce.jobhistory.webapp.address",
		// "192.168.99.101:19888");
		// conf.set("yarn.resourcemanager.webapp.address",
		// "192.168.99.101:8088");
		/* 或者使用下列方式 （如果*.xml在classpath目录下，即使不写这些，也会自动加载这些*.xml）*/
		// conf.addResource("core-site.xml");
		// conf.addResource("hdfs-site.xml");
		// conf.addResource("mapred-site.xml");
		// conf.addResource("yarn-site.xml");
		//设置hprof无效，需要进一步实验
//		conf.setBoolean(MRJobConfig.TASK_PROFILE_PARAMS, true);
//		conf.set(MRJobConfig.TASK_PROFILE_PARAMS, "-agentlib:hprof=cpu=samples,heap=sites,depth=6,force=n,thread=y,verbose=n,file=%s");
//		conf.set(MRJobConfig.NUM_MAP_PROFILES, "0-2");
//		conf.set(MRJobConfig.NUM_REDUCE_PROFILES, "");
		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
		if (otherArgs.length != 2) {
			System.err.println("Usage: wordcount <in> <out>");
			System.exit(2);
		}
		Job job = Job.getInstance(conf, "word count1");
		job.setJarByClass(WordCount.class);
		// 当以集群方式运行时，必须执行下列语句
		((JobConf) job.getConfiguration()).setJar(jarFile.toString());
		job.setMapperClass(TokenizerMapper.class);
		job.setCombinerClass(IntSumReducer.class);
		job.setReducerClass(IntSumReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
		logger.info("完成！");
	}
}
